// 公共BaseModel
const cloud = require('wx-server-sdk');
cloud.init({
 env: 'yun-duan-8693e',
 traceUser: true,
});
// 环境
// cloud.init({ env: process.env.Env })
const db = cloud.database();
const _ = db.command //普通查询操作符
const $ = db.command.aggregate //聚合查询操作符

/**
 * 查询处理 
 * @param  {object} model       集合名称
 * @param  {String} id          查询id
 * @return  {object|null}       查找结果
 */
const findById = (model, fields = {} , id ) => {
  console.log(id)
  try {
    return db.collection(model)
      .doc(id)
      .field(fields) 
      .get()
  } catch (e) {
    console.error(e)
  }
}

/**
 * 查询处理 带多条件的
 * @param  {object} model         集合名称
 * @param  {Object} [options={}]    查询条件
 * @param  {Number} [page]        开始记录数
 * @param  {Number} [size]        每页显示的记录数
 * @return  {object|null}         查找结果
 */
const query = (model, fields = {}, options = {}, page = 0, size = 10, order = { name: '_id', orderBy:'asc'} ) => {
  try {
    return db.collection(model)
    .where(options)
    .field(fields) 
    .skip(page)
    .limit(size)
    .orderBy(order.name, order.orderBy)
    .get()

  } catch (e) {
    console.error(e)
  }
}
const query3 = (model, fields = {}, options = {}, page = 0, size = 10, order = { name: '_id', orderBy:'asc'} ) => {
  try {
    return db.collection(model)
    .where({
      _id: _.in(options)
    })
    .field(fields) 
    .skip(page)
    .limit(size)
    .orderBy(order.name, order.orderBy)
    .get()

  } catch (e) {
    console.error(e)
  }
}
//** 聚合查询 商品分类**
const query1 = (model, fields = {}, options = {}, page = 0, size = 10, order = { name: '_id', orderBy:'asc'} ) => {
  try {
    return db.collection(model).aggregate()
    .match({
      idx:options.rightNav
    })
    .project({
      _id: options.rightNav,
      name: 1,
      data: $.filter({
        input: '$data',
        as: 'this',
        cond: $.eq(['$$this.idx', options.curNav])
      }),
    })
    .project({
      _id: options.rightNav,
      name: 1,
      data: $.slice(['$data',page*size,(page+1)*size]),
      totalStaff: $.size('$data'),
    })
    .end()
    // .then(res=>{
    //   console.log(res)
    // })

  } catch (e) {
    console.error(e)
  }
}
//** 聚合查询 关键词搜索商品**
const query2 = (model, fields = {}, options = {}, page = 0, size = 10) => {
  console.log(options)
  console.log(page)
  console.log(size)
  try {
    return db.collection(model).aggregate()
    .unwind("$data")//拆分嵌套的data
    .match({//模糊查询关键词
      'data.name':{
        $regex:'.*'+ options,
        $options: 'i'
      }
    })
    .limit(10)
    .group({//通过唯一_id合并
      _id:"_id",
      data:$.push("$data")
    })
    .project({
      _id: 0,
    })
    .end()
    // .then(res=>{
    //   console.log(res)
    // })

  } catch (e) {
    console.error(e)
  }
}
//** 聚合查询 商品详情**
const query4 = (model, fields = {}, options = {}, page = 0, size = 10) => {
  console.log(options)

  try {
    return db.collection(model).aggregate()
    .unwind("$data")//拆分嵌套的data
    .match({
      'data._id': options
    })
    .group({//通过唯一_id合并
      _id:"_id",
      data:$.push("$data")
    })
    .project({
      _id: 0
    })
     .unwind("$data")//拆分嵌套的data
    .replaceRoot({
      newRoot: '$data'
    })
    .lookup({
      from: 'detail',
      let: {
        order_book: '$_id',
      },
      pipeline: $.pipeline()
        .match(_.expr(
          $.eq(['$_id', '$$order_book'])
          ))
        .project({
          _id: 0,
          thumb:1,
          title:1
        })
        .done(),
        as: 'bookList'
    })
    .unwind("$bookList")//拆分嵌套的data
    .addFields({
      thumb: '$bookList.thumb',
      title:'$bookList.title'
    })
    .project({
      bookList:0
    })
    .end()
    // .then(res=>{
    //   console.log(res)
    // })

  } catch (e) {
    console.error(e)
  }
}

/**
 * 新增处理
 * @param  {object} model  集合名称
 * @param  {object} params 参数
 * @return {object| null}  操作结果
 */
const add = (model, params) => {
  try {
    return db.collection(model).add({
      data: params
    });
  } catch (e) {
    console.error(e);
  }
}

/**
 * 编辑处理
 * @param  {object} model      集合名称
 * @param  {object} params     参数
 * @param  {object} options    字段
 * @param  {object} num        数量
 * @return {object|null}       操作结果
 */
const update = (model, params, options, num) => {
  // let id = params._id
  // delete params._id
  try {
    return db.collection(model).doc(params)
    .update({
      data: {
        [options]: _.set(num)
      }
    })
  } catch (e) {
    console.error(e);
  }
}
const update1 = (model, params, options) => {
  try {
    return db.collection(model).doc(params)
    .update({
      data:options
    })
  } catch (e) {
    console.error(e);
  }
}
/**
 * 删除单条结果
 * @param  {object} model      集合名称
 * @param  {String} id         参数
 * @return {object|null}       操作结果
 */
const removeSingle = (model, id) => {
  try {
    return  db.collection(model).doc(id).remove()
  } catch (e) {
    console.error(e)
  }
}

/**
 * 删除多条结果
 * @param  {object} model      集合名称
 * @param  {String} id         参数
 * @return {object|null}       操作结果
 */
const removeMultiple = (model, id) => {
  try {
    return db.collection(model).where({
      _id: _.in(id)
    }).remove()
  } catch (e) {
    console.error(e)
  }
}



module.exports = {
  query,
  query1,
  query2,
  query3,
  query4,
  findById,
  add,
  update,
  update1,
  removeSingle,
  removeMultiple
}